﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace SpridTest
{
    public partial class Form1 : Form
    {
        List<Thread> threadList = new List<Thread>();

        Thread thread = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            #region MyRegion
            /*
            DateTime dtStart = DateTime.Now;
            button1.Enabled = false;
            button2.Enabled = true;
            button3.Enabled = false;
            button4.Enabled = true;

            int page = 0;
            int count = 0;
            int personCount = 0;
            textBox1.Text = "已完成页数:0";
            int index = 0;
            //for (int i = 0; i <= 10; i++)
            //{
            thread = new Thread(new ParameterizedThreadStart(delegate (Object obj)
            {
                //for (int j = 0; j <= 10; j++)
                //{
                try
                {
                    //index = (Convert.ToInt32(obj) - 1) * 10 + j;
                    string pageHtml = HttpRequestUtil.GetPageHtml("http://you.163.com/act/pub/YOHVdVGdD9.html");
                    //正则表达式
                    Regex regA = new Regex("<a[\\s]+target=\"_blank([^<>]*?)[\\s]+href=\"([^\"]*?)\"");
                    Regex regImg = new Regex("<img[\\s]+class=\"j-thumb\"[\\s]+src=\"([^\"]*?)\"");

                    MatchCollection mc = regA.Matches(pageHtml);
                    foreach (Match match in mc)
                    {
                        int start = match.ToString().IndexOf("href=\"");
                        string url = match.ToString().Substring(start);

                        int end = url.IndexOf("&");
                        url = url.Substring(6, end);
                        if (url.IndexOf("/") != 0)
                        {
                            string imgPageHtml = HttpRequestUtil.GetPageHtml(url);

                            personCount++;

                            textBox2.Invoke(new Action(delegate () { textBox2.Text = "已完成条数" + personCount.ToString(); }));
                            MatchCollection mcImgPage = regImg.Matches(imgPageHtml);
                            foreach (Match matchImagePage in mcImgPage)
                            {
                                start = matchImagePage.ToString().IndexOf("src=\"");
                                string imgUrl = matchImagePage.ToString().Substring(start + 5);
                                end = imgUrl.IndexOf("\"");
                                imgUrl = imgUrl.Substring(0, end);
                                if (imgUrl.IndexOf("http://yanxuan.nosdn.127.net") == 0)
                                {
                                    try
                                    {
                                        HttpRequestUtil.HttpDownLoadFile(imgUrl);
                                        count++;
                                        textBox3.Invoke(new Action(delegate ()
                                        {
                                            textBox3.Text = "已下载图片数 " + count.ToString();
                                            DateTime dt = DateTime.Now;
                                            double time = dt.Subtract(dtStart).TotalSeconds;
                                            if (time > 0)
                                            {
                                                textBox4.Text = "速度：" + (count / time).ToString("0.0") + "张";
                                            }
                                        }));
                                    }
                                    catch (Exception ex)
                                    {
                                        string errorMsg = ex.Message.ToString();
                                    }
                                    Thread.Sleep(1);
                                }

                            }
                        }
                    }

                }
                catch (Exception ex1)
                {
                    string error = ex1.Message.ToString();
                }
                page++;
                textBox1.Invoke(new Action(delegate () { textBox1.Text = "已完成页数:" + page.ToString(); }));
                if (page == 100)
                {
                    button1.Invoke(new Action(delegate () { button1.Enabled = true; }));

                    MessageBox.Show("完成！");
                }
                //}
            }));
            thread.Start(0);
            threadList.Add(thread);
            */

            #endregion
            /*
            HttpWebRequest request = WebRequest.Create("http://hotels.ctrip.com/###") as HttpWebRequest;
            request.Method = "get";
            request.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送post请求
            Stream responseStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            //返回结果网页的html代码
            string content = sr.ReadToEnd();

            string path = @"../reg.html";
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs,Encoding.UTF8);
            fs.SetLength(0);//首先把文件清空了。
            sw.Write(content);//写你的字符串。
            sw.Close();
            */
            string path = @"../result.txt";
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            Hashtable hashTable = new Hashtable();
            XmlDocument doc = new XmlDocument();
            doc.Load("../reg.html");
            XmlNode nodes = doc.SelectSingleNode("//*[@id=\"nearbyPopCity\"]");
            foreach (XmlNode xn in nodes.ChildNodes)
            {
                string cityName = xn.InnerText;
                string cityUrl = "http://hotels.ctrip.com/"+((XmlElement)xn).GetAttribute("href");
                //hashTable.Add(cityName, cityUrl);
                sw.WriteLine(cityName + ":" + cityUrl);
            }
            sw.Close();
        }
        /// <summary>
        /// 暂停
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            button1.Invoke(new Action(delegate ()
            {
                foreach (Thread t in threadList)
                {
                    if (t.ThreadState == ThreadState.Suspended)
                    {
                        t.Resume();
                    }
                    t.Abort();
                }
                button1.Enabled = true;
                button2.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
            }));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            foreach (Thread t in threadList)
            {
                t.Abort();
            }
        }
        /// <summary>
        /// 继续
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            foreach (Thread t in threadList)
            {
                t.Suspend();
            }
            button3.Enabled = false;
            button4.Enabled = true;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            foreach (Thread t in threadList)
            {
                if(t.ThreadState==ThreadState.Suspended)
                {
                    t.Resume();
                }
                button3.Enabled = true;
                button4.Enabled = false;
            }
        }
    }
}
